package com.hoyue.dao.impl;

import com.hoyue.bean.Info;
import com.hoyue.dao.InfoDao;
import com.hoyue.utils.C3P0Utils;
import com.hoyue.utils.Page;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Hoyue_network1
 * @version 1.0
 * Creat by 2018/8/24 16:32
 */
public class InfoDaoImpl extends PageDaoImpl<Info> implements InfoDao{

	QueryRunner qr = C3P0Utils.getQueryRunner();

	@Override
	public List<Info> getAllInfo() throws SQLException {
		String sql = "SELECT * FROM information";

		return qr.query(sql,new BeanListHandler<>(Info.class));

	}

	@Override
	public void addInfo(Info info) throws SQLException {
		String sql = "INSERT INTO information (title,address,url,picture,time) VALUES (?,?,?,?,CURDATE())";

		Object[] params = new Object[4];

		params[0] = info.getTitle();
		params[1] = info.getAddress();
		params[2] = info.getUrl();
		params[3] = info.getPicture();

		qr.update(sql,params);
	}

	@Override
	public void deleteInfo(int id) throws SQLException {
		String sql = "DELETE FROM information where id=?";

		qr.update(sql,id);
	}

	@Override
	public void updateInfo(Info info) throws SQLException {
		String sql = "UPDATE information SET title=?, address=?, url=?, picture=?, time=? WHERE id=?";

		java.util.Date date = new java.util.Date();
		Timestamp timeStamp = new Timestamp(date.getTime());

		qr.update(sql,info.getTitle(),info.getAddress(),info.getUrl(),info.getPicture(),timeStamp,info.getId());
	}

	@Override
	public String getAddressById(int id) throws SQLException {
		String sql = "SELECT address FROM information WHERE id=?";

		return qr.query(sql,new ScalarHandler<>(),id);
	}

	@Override
	public List<Info> searchInfo(String search) throws SQLException {
        String sql = "SELECT * FROM information WHERE title LIKE '%" + search + "%'";
		return qr.query(sql,new BeanListHandler<>(Info.class));
	}

	public Page<Info> getPage(int page,String tableName) throws SQLException {
		Page<Info> infos =  getListByPage(page,tableName);

		return infos;
	}

}
